/**
 * 
 * @param {String} url - 上传地址
 * @param {*} config - 上传的配置具体参考uni.uploadfile文档
 * @return {Array} 上传结果
 */
export default class upload {
	constructor(config = {}) {
		setTimeout(() => {
			this.url = uni.$lu?.config?.http?.baseURL
			this.config = uni.$lu?.config?.http?.config;
		}, 0)
	}

	/**
	 * @description 获取配置
	 */
	getConfig() {
		console.log('上传配置:', this.config)
		console.log('上传地址:', this.url)
	}

	/**
	 * @description 上传图片
	 * @returns {Promise} 上传结果
	 */
	img() {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: this.config?.count ?? 1, // 最多可以选择的图片张数
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['camera', 'album'], // camera调用相机拍照，album是打开手机相册
				success: (res) => {
					this.execute(res.tempFilePaths, resolve)
				}
			})
		})
	}

	/**
	 * @description 上传视频
	 * @returns {Promise} 上传结果
	 */
	video() {
		return new Promise((resolve, reject) => {
			uni.chooseVideo({
				sourceType: ["album", "camera"],
				maxDuration: this.config?.maxTime ?? 15,
				success: (res) => {
					this.execute([res.tempFilePath], resolve)
				}
			})
		})
	}

	/**
	 * @description 具体实现
	 * @param {Array} task 
	 * @param {Promise} resolve 
	 * @returns {Array} 上传结果
	 */
	async execute(task = [], resolve) {
		if (!task.length) return new Error('请先上传图片或视频')
		try {
			uni.showLoading({ title: '上传中' })
			const allUpload = task.map(item => {
				return new Promise(async (resolve, reject) => {
					const res = uni.$lu.http.upload(url, { ...this.config, filePath: item }).catch(err => { reject(err) })
					resolve(res.data)
				})
			})
			const results = await Promise.all(allUpload)
			uni.hideLoading()
			await uni.$lu.sleep(500)
			uni.$lu.toast('上传成功')
			resolve(results)
		} catch (error) {
			reject(error)
		}
	}

}